package com.ligq.h265toupinpush.call

import android.annotation.SuppressLint
import android.media.*
import android.os.Handler
import android.os.HandlerThread
import android.util.Log

private const val SAMPLE_RATE_HZ = 44100
private const val CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO
private const val AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT

class AudioRecordLive(private val socketLive: SocketLive? = null) {
    private lateinit var audio: AudioRecord
    private var isRecording = false
    private lateinit var workHandler: Handler
    private lateinit var audioTrack: AudioTrack

    init {
        initAudioTrack()
    }

    @SuppressLint("MissingPermission")
    fun startRecord() {
        if (!this::workHandler.isInitialized) {
            val handlerThread = HandlerThread("audio_record")
            handlerThread.start()
            workHandler = Handler(handlerThread.looper)
        }
        val minBufferSize =
            AudioRecord.getMinBufferSize(SAMPLE_RATE_HZ, CHANNEL_CONFIG, AUDIO_FORMAT)
        audio = AudioRecord(
            MediaRecorder.AudioSource.MIC, SAMPLE_RATE_HZ, CHANNEL_CONFIG,
            AUDIO_FORMAT, minBufferSize
        )
        audio.startRecording()
        isRecording = true
        val data = ByteArray(minBufferSize)
        workHandler.post {
            while (isRecording) {
                audio.read(data, 0, minBufferSize)
//                FileUtils.writeBytes("audio.pcm", data)
                socketLive?.sendData(2, data)
            }
        }
    }

    private fun initAudioTrack() {
        val minBufferSize =
            AudioTrack.getMinBufferSize(SAMPLE_RATE_HZ, AudioFormat.CHANNEL_OUT_MONO, AUDIO_FORMAT)
        audioTrack = AudioTrack(
            AudioManager.STREAM_MUSIC,
            SAMPLE_RATE_HZ,
            AudioFormat.CHANNEL_OUT_MONO,
            AUDIO_FORMAT,
            minBufferSize,
            AudioTrack.MODE_STREAM
        )
        audioTrack.setVolume(16f)
        audioTrack.play()
    }

    fun playMusic(buffer: ByteArray) {
        val ret = audioTrack.write(buffer, 1, buffer.size - 1)
        Log.d(TAG, "playMusic: ret=$ret")
    }
}